package br.com.escolaespacocrianca.fineec.business;

import java.util.List;

import org.hibernate.Session;

import br.com.caelum.vraptor.ioc.Component;
import br.com.escolaespacocrianca.fineec.model.Student;

@Component
public class StudentBusiness extends EntityBusiness<Student> {
		
	public StudentBusiness(Session session) {
		super(session, new Student());
	}

	@SuppressWarnings("unchecked")
	public List<Student> searchByName(String studentName) {

		List<Student> students = session.createQuery(
		"from Student as s where upper(s.name) like  '%" + studentName.toUpperCase() + "%' and s.deleted = false").list();

		return students;
	}
	
	@Override
	protected void updateEntityInformations(Student student, Student studentToUpdate) {
		studentToUpdate.setName(student.getName());
		studentToUpdate.setGender(student.getGender());
		studentToUpdate.setBirthday(student.getBirthday());
		studentToUpdate.setNacionality(student.getNacionality());
		studentToUpdate.setCitizenship(student.getCitizenship());
		studentToUpdate.setAddress(student.getAddress());
		studentToUpdate.setOtherSponsors(student.getOtherSponsors());
		studentToUpdate.setFirstSponsor(student.getFirstSponsor());
		studentToUpdate.setSecondSponsor(student.getSecondSponsor());
		studentToUpdate.setFinancialSponsor(student.getFinancialSponsor());
		
		if (student.getEnrollmentNumber() == null || student.getEnrollmentNumber() == 0){
			studentToUpdate.setEnrollmentNumber(generateNextEnrollmentNumber());
		}else{
			studentToUpdate.setEnrollmentNumber(student.getEnrollmentNumber());
		}
	}
	
	public boolean existStudentWithNumber(Integer enrollmentNumber){
		
		Student student = (Student)session.createQuery("from Student as s where s.enrollmentNumber = " + enrollmentNumber ).uniqueResult();
		if (student == null){
			return false;
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public boolean existStudentWithName(String studentName){
		
		List<Student> students = (List<Student>)session.createQuery("from Student as s where upper(s.name) like '%" + studentName.trim().toUpperCase() + "%'" ).list();
		if (students == null || students.size() == 0){
			return false;
		}
		return true;
	}
	
	protected Integer generateNextEnrollmentNumber() {
		
		Integer max = (Integer)session.createQuery(
				"select max(enrollmentNumber) as max from Student s").uniqueResult();
		
		if (max == null){
			max = 0;
		}
		
		max = max + 1;
		
		if (max < 300){
			max = 300;
		}
		
		return max;
	}

	@Override
	protected void beforeDelete(Student t) {
		
	}
}
